#!/usr/bin/php -q
<?PHP
/* Copyright 2005-2023, Lime Technology
 * Copyright 2012-2023, Bergware International.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License version 2,
 * as published by the Free Software Foundation.
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 */
?>
<?
$docroot ??= ($_SERVER['DOCUMENT_ROOT'] ?: '/usr/local/emhttp');
require_once "$docroot/webGui/include/publish.php";

function my_scale($value, &$unit) {
  $units = ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi','Yi'];
  $size = count($units);
  $base = $value ? floor(log($value, 1024)) : 0;
  if ($base>$size) $base = $size-1;
  $value /= pow(1024, $base);
  $decimals = $value>=100 ? 0 : ($value>=10 ? 1 : (round($value*100)%100===0 ? 0 : 2));
  if (round($value,-1)==1000) {$value = 1; $base++;}
  $unit = $units[$base].'B';
  return number_format($value, $decimals, '.', $value>9999 ? ',':'');
}

$md5_old = -1;
while (true) {
  $now = time();
  $echo = [];
  unset($dump);
  exec('wg show all dump',$dump);
  foreach ($dump as $row) {
    $row = preg_split('/\s+/',$row);
    if (count($row)>5) $echo[] = [$row[0], $row[5]?$now-$row[5]:0, my_scale($row[6],$unit)." $unit", my_scale($row[7],$unit)." $unit"];
  }
  $echo = json_encode($echo);
  $md5_new = md5($echo,true);
  if ($md5_new !== $md5_old) {
    $md5_old = publish('wireguard',$echo)!==false ? $md5_new : -1;
  }
  sleep(1);
}
?>
